package handler

import (
	"context"
	"dh.com/shop/srv/product/proto/product"
	"encoding/json"
	api "github.com/micro/go-micro/api/proto"
	"github.com/micro/go-micro/client"
	"github.com/micro/go-micro/errors"
	"net/http"
)

//Product
type Product struct {
	Client product.ProductService
}

//NewProduct
func NewProduct(cli client.Client) *Product {
	cliProduct := product.NewProductService("com.dh.shop.srv.product", cli)
	return &Product{Client: cliProduct}
}

// Product.Call is called by the API as /product/call with post body {"name": "foo"}
func (pro *Product) Add(ctx context.Context, req *api.Request, rsp *api.Response) error {

	p := &product.TProduct{}
	err := json.Unmarshal([]byte(req.Body), p)
	if err != nil {
		return errors.InternalServerError("com.dh.shop.api.product.Add", err.Error())
	}

	// make request
	_, err = pro.Client.Add(ctx, &product.AddMessage{Product: p})
	if err != nil {
		return errors.InternalServerError("com.dh.shop.api.product.Add", err.Error())
	}

	rsp.StatusCode = http.StatusOK
	rsp.Body = "添加成功！"

	return nil
}

// Product.Call is called by the API as /product/call with post body {"name": "foo"}
func (pro *Product) FindAll(ctx context.Context, req *api.Request, rsp *api.Response) error {

	// make request
	response, err := pro.Client.FindAll(ctx, &product.FindAllRequest{})
	if err != nil {
		return errors.InternalServerError("com.dh.shop.api.product.FindAll", err.Error())
	}

	rsp.StatusCode = http.StatusOK

	rst, err := json.Marshal(response)
	if err != nil {
		return errors.InternalServerError("com.dh.shop.api.product.FindAll", err.Error())
	}

	rsp.Body = string(rst)

	return nil
}
